package dse.messages.updatingshares;

import dse.DataObject;
import dse.Experiment;
import dse.ExperimentRecorder;
import dse.Node;
import dse.messages.Message;
import dse.messages.MessageHandler;
import dse.messages.MessagePurpose;
import dse.messages.MessageSender;
import dse.messages.MessageType;
import dse.messages.singleversion.ShareDownloader;

public class UpdateShareMessageHandler extends MessageSender implements
		MessageHandler
{
	private DataObject dobj;
	private int shareIndex;
	private ShareDownloader shareDownloader;
	
	public UpdateShareMessageHandler (
			Experiment experiment, 
			DataObject dobj, 
			int shareIndex,
			ShareDownloader shareDownloader
			)
	{
		super(experiment);
		
		this.dobj = dobj;
		this.shareIndex = shareIndex;
		this.shareDownloader = shareDownloader;
	}
	@Override
	public boolean acceptMessage(Message message) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void messageInterupted(ExperimentRecorder recorder, Message message,
			double timeLeft) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgIntrpt: " + message, timeLeft);
		shareDownloader.shareUpdateFailed(
				recorder, dobj, shareIndex, timeLeft
				);
	}

	@Override
	public void messageReceived(ExperimentRecorder recorder, Message message,
			double timeLeft) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgRcvd: " + message, timeLeft);
		if (message.messageType() != MessageType.UpdateShare) {
			recorder.warn(
					"UpdateShareMessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}	
		// What do we know about the share?
		Node receiver = message.to();
		Node sender = message.from();
		if(receiver.isHosting(dobj, shareIndex) || (!receiver.isHosting(dobj)))
		{
			Message m = super.createShareDataTransferMessage(
					sender, receiver, dobj, shareIndex, 
					MessagePurpose.DataObjectUpdate, shareDownloader
					);
			recorder.debug(this, "new msg: " + m, timeLeft);
			//experiment.messageQueue().enqueueMessageInPeriod(m, timeLeft);
		}
		else
		{
			shareDownloader.shareUpdateFailed(
					recorder, dobj, shareIndex, timeLeft
					);
		}
	}
}
